package com.dianmi.seckill.common.advice;

import lombok.Data;

/**
 * @author xieqiaofu
 * @date 2020/11/24
 */
@Data
public class ResponseData<T> {

    private int resultcode;

    private String msg;

    private String errormsg;

    private T data;

    public static ResponseData success() {
        return success(ResponseCode.SUCCESS);
    }

    public static <T> ResponseData<T> success(T data) {
        return success(ResponseCode.SUCCESS, data);
    }

    public static <T> ResponseData<T> success(ResponseCode code) {
        return success(code, null);
    }

    public static <T> ResponseData<T> success(String msg) {
        return newInstance(ResponseCode.SUCCESS.getCode(), msg, null, null);
    }

    public static <T> ResponseData<T> success(ResponseCode code, T t) {
        return newInstance(code.getCode(), code.getMsg(), null, t);
    }

    public static <T> ResponseData<T> failed(ResponseCode code) {
        return failed(code.getCode(), code.getMsg());
    }

    public static <T> ResponseData<T> failed(String errormsg) {
        return failed(ResponseCode.SERVICE_ERROR.getCode(), errormsg);
    }

    public static <T> ResponseData<T> failed(int resultCode, String errormsg) {
        return newInstance(resultCode, null, errormsg, null);
    }

    public static <T> ResponseData<T> failed(int resultcode, T data) {
        return newInstance(resultcode, null,null, data);
    }

    private static <T> ResponseData<T> newInstance(int resultCode, String msg, String errormsg, T data) {
        ResponseData<T> responseData = new ResponseData<T>();
        responseData.setResultcode(resultCode);
        responseData.setMsg(msg);
        responseData.setErrormsg(errormsg);
        responseData.setData(data);
        return responseData;
    }

    public static <T> T attainData(ResponseData<T> responseData) {
        if (null != responseData && ResponseCode.SUCCESS.getCode() != responseData.getResultcode()) {
            throw new ServiceException(responseData.getResultcode(), responseData.getMsg());
        }
        return null == responseData ? null : responseData.getData();
    }
}
